<script setup lang='ts'>
const props = defineProps({
  currentRow: {
    type: Object,
    default: () => ({}),
  },
})
const emit = defineEmits(['done'])
const visible = defineModel<boolean>()
const uuid = computed(() => props.currentRow.uuid)
const title = computed(() => uuid.value ? '修改角色' : '添加角色')

const policError = ref('')
const formRef = ref()
const checkedGroup = ref({})
const form = reactive({
  name: '',
  description: '',
  policyUuids: [],
})
const formRules = {
  name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
  description: [{ required: false, message: '请输入描述', trigger: 'blur' }],
}
function confirm() {
  formRef.value?.validate(async (valid) => {
    if (!valid)
      return
    const checkedUuids = Object.values(checkedGroup.value).flat()
    if (checkedUuids.length) {
      policError.value = ''
      form.policyUuids = checkedUuids
    }
    else {
      policError.value = '请选择权限'
      return
    }
    if (uuid.value)
      emit('done', { ...form, uuid: uuid.value })
    else
      emit('done', form)
  })
}

const permissGroup = ref<any>({})
// 把权限按照权限分组
function permissionGroup(permissionList) {
  return permissionList.reduce((acc, cur) => {
    if (!acc[cur.type])
      acc[cur.type] = []

    acc[cur.type].push(cur)
    return acc
  }, {})
}

async function getPermission() {
  const result = await useRequest('QueryPolicy', { conditions: [], sortBy: 'sortId', sortDirection: 'asc', limit: 200 }) as any
  permissGroup.value = result.success ? permissionGroup(result.inventories) : {}
}

async function getRolePolicy() {
  const { inventories = [] } = await useRequest('QueryRolePolicy', { conditions: [
    { name: 'roleUuid', op: '=', value: uuid.value },
  ] }) as any
  form.policyUuids = inventories.map(item => item.policyUuid)
  echoChecked()
}
/** 回显选中 */
function echoChecked() {
  Object.entries(permissGroup.value).forEach(([key, list]) => {
    // 已有的权限在某一分组中，则把这些权限的uuid放入checkedGroup中
    form.policyUuids.forEach((checkedUuid) => {
      if (list.map(item => item.uuid).includes(checkedUuid)) {
        if (!checkedGroup.value[key])
          checkedGroup.value[key] = [checkedUuid]
        else
          checkedGroup.value[key].push(checkedUuid)
      }
    })
  })
}
watch(visible, async (val) => {
  if (val) {
    await getPermission()
    const { uuid, name, description } = props.currentRow
    if (uuid) {
      form.name = name
      form.description = description
      getRolePolicy()
    }
  }
  else {
    permissGroup.value = {}
    checkedGroup.value = {}
    formRef.value?.resetFields()
  }
})

const rihts = [
  {
    name: '流程发起',
    uuid: '1',
  },
  {
    name: '售前审批',
    uuid: '2',
  },
  {
    name: '测试审批',
    uuid: '3',
  },
  {
    name: '流程关停',
    uuid: '4',
  },

]
</script>

<template>
  <el-dialog v-model="visible" :title="title" width="720px" append-to-body :close-on-click-modal="false">
    <el-form ref="formRef" :model="form" label-width="90px" :rules="formRules">
      <el-form-item label="角色名" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="form.description" type="textarea" placeholder="请输入角色描述" />
      </el-form-item>
      <el-form-item label="权限" prop="policyUuids" :error="policError">
        <el-checkbox v-for="item in rihts" :key="item.uuid" :value="item.uuid">
          {{ item.name }}
        </el-checkbox>
        <!-- <div v-for="(list, name) in permissGroup" :key="name" class="flex">

          <h4 class="min-w-22 text-base font-bold">
            {{ name }}
          </h4>
          <el-checkbox-group v-model="checkedGroup[name]">
            <el-checkbox v-for="item in list" :key="item.uuid" :value="item.uuid">
              {{ item.name }}
            </el-checkbox>
          </el-checkbox-group>
        </div> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click=" visible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="confirm">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang='scss'>

</style>
